using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Wicresoft.RDW.Presentation;
using Resources;
using Wicresoft.RDW.Utility;
using System.Text;
using Wicresoft.RDW.UserControls;
using System.IO;
using System.Configuration;


namespace Wicresoft.RDW.Request
{
    public partial class VisitApply : BasePage
    {
        protected override void OnPreLoad(EventArgs e)
        {
            FobiddenBack();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            RequestBasic.RequestTypeChanged += new UserControls.RequestBasicControl.LoadUserControl(RequestBasic_RequestTypeChanged);

            if (!IsPostBack)
            {
                phVisit.Visible = false;
                phRent.Visible = false;
                phTesting.Visible = false;

                this.IntialCulture();
                this.InitControlResource();
                this.InitialButton();
            }
        }

        public override void InitControlResource()
        {
            this.btnReturn.Text = Resources.NameResource.lbtnReturn;
            this.btnApprov.Text = Resources.NameResource.Approve;
            this.btnRejected.Text = Resources.NameResource.Rejected;
            this.btnAskForMore.Text = Resources.NameResource.AskForMore;
            this.btnClose.Text = Resources.NameResource.OK;
            this.btnSaveDraft.Text = Resources.NameResource.SaveDraft;
            this.btnSave.Text = Resources.NameResource.btnSubmit;
            this.btnCancel.Text = Resources.NameResource.btnCancel;
            this.btnSaveAskForMore.Text = Resources.NameResource.btnSubmit;
            this.txtConclusionValidator.ErrorMessage = string.Format(Resources.NameResource.OverMaxLength, 100);
        }

        void RequestBasic_RequestTypeChanged(int typeId, int labId)
        {
            switch ((RequestType)typeId)
            {
                case RequestType.Visit:
                    phRent.Visible = false;
                    phTesting.Visible = false;
                    phVisit.Visible = true;
                    VisitRequest.LabId = labId;
                    break;
                case RequestType.SiteBorrow:
                    phVisit.Visible = false;
                    phTesting.Visible = false;
                    phRent.Visible = true;
                    break;
                case RequestType.Testing:
                    phVisit.Visible = false;
                    phRent.Visible = false;
                    phTesting.Visible = true;
                    break;
                default:
                    phVisit.Visible = false;
                    phRent.Visible = false;
                    phTesting.Visible = false;
                    break;
            }
        }

        public void IntialCulture()
        {
            if (Id > 0)
            {
                if (string.Equals(GetQueryString("pageStatus"), PageStatus.View.ToString(), StringComparison.CurrentCultureIgnoreCase)
                    || string.Equals(GetQueryString("pageStatus"), PageStatus.Readonly.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    PageStatus = PageStatus.Readonly;
                    btnSaveDraft.Visible = false;
                    btnSave.Visible = false;
                    btnCancel.Visible = false;
                    btnReturn.Visible = true;
                }
                else if (string.Equals(GetQueryString("pageStatus"), PageStatus.Edit.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    PageStatus = PageStatus.Edit;
                    btnReturn.Visible = false;
                }
                var request = RequestPresent.GetById(Id);
                if (!IsCurrentApplyUser)
                {
                    PageStatus = PageStatus.Readonly;
                    btnSaveDraft.Visible = false;
                    btnSave.Visible = false;
                    btnCancel.Visible = false;
                    btnReturn.Visible = true;
                }
                if (CurrentUserId == 0 && !string.IsNullOrEmpty(GetQueryString("language")))
                {
                    if (string.Equals(GetQueryString("language"), Utility.Language.EN.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        this.Page.Culture = "en-US";
                        this.Page.UICulture = "en-US";
                        Language = Utility.Language.EN;
                    }
                    else
                    {
                        this.Page.Culture = "zh-CN";
                        this.Page.UICulture = "zh-CN";
                        Language = Utility.Language.CN;
                    }
                }
            }

            else
            {
                PageStatus = PageStatus.New;
                btnReturn.Visible = false;
            }
            this.commentValidate.ErrorMessage = Resources.NameResource.Comments + Resources.CommonResource.NotNull;

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                RequestBasic_RequestTypeChanged(RequestBasic.RequestData.RequestType, RequestBasic.RequestData.LabId);
                return;
            }
            Model.Request request = RequestBasic.RequestData;
            if (request.RequestType == (int)RequestType.Visit)
            {
                if (VisitRequest.VisitValidateForm == false)
                {
                    RequestBasic_RequestTypeChanged(RequestBasic.RequestData.RequestType, RequestBasic.RequestData.LabId);
                    return;
                }
            }
            if (this.Id > 0 && GetRequestStatus(Id) == RequestStatus.AskForMore)
            {
                var commentBox = ((TextBox)RequestBasic.FindControl("txtComments")).Text;
                if (!string.IsNullOrEmpty(commentBox))
                {
                    this.Comments = Server.HtmlEncode(CurrentUserName + ":" + commentBox + "<br/>");
                    SaveDraftOrAskForMoreRequest(this.Id);
                }
            }
            else
            {
                Save(RequestStatus.Pending);
                ApplySendMail();
            }
            Response.Redirect("/MyWork/View.aspx");

        }
        private void ApplySendMail()
        {
            var centerManagerRoleId = int.Parse(ConfigurationManager.AppSettings["CenterManagerRoleId"]);
            var centerManagerEmailList = RequestPresent.GetCenterManagerEmails(centerManagerRoleId);
            StringBuilder content = new StringBuilder();
            var requestId = RequestPresent.GetList().Last().RequestId;
            var dns = RequestPresent.GetLinkAddressByRequestId(requestId, Request.Url.Host, true, Request.Url.Port, Language.EN, false);
            string email = string.Empty;
            string officePhone = string.Empty;
            RequestPresent.GetEmailPhoneById(CurrentUserId, out email, out officePhone);
            content.Append(dns);
            content.Append("^");
            content.Append(email);
            content.Append("^");
            content.Append(officePhone);
            content.Append("^");
            dns = RequestPresent.GetLinkAddressByRequestId(requestId, Request.Url.Host, true, Request.Url.Port, Language.CN, false);
            content.Append(dns);
            content.Append("^");
            content.Append(email);
            content.Append("^");
            content.Append(officePhone);
            MailPresent.SendMail(EmailTemplate.ApprovalReminder, content.ToString(), centerManagerEmailList, "");
        }

        protected void btnSaveDraft_Click(object sender, EventArgs e)
        {
            //ValidationSummary1.HeaderText += "<ul><li>hello!</li></ul>";
            if (RequestBasic.ValidateForm == false)
            {
                RequestBasic_RequestTypeChanged(RequestBasic.RequestData.RequestType, RequestBasic.RequestData.LabId);
                return;
            }
            Save(RequestStatus.Draft);
            Response.Redirect("/MyWork/View.aspx");

        }

        protected void Save(RequestStatus status)
        {
            if (Id > 0)
            {

                var request = RequestPresent.GetById(this.Id);
                RequestBasic.RequestData.CopeProperties(request);
                request.CreateTime = DateTime.Now;
                request.Status = (int)status;

                if (request.RequestType == (int)RequestType.Visit)
                {
                    VisitRequest.VisitProductUpdate();
                    VisitRequest.VisitRequestData.CopeProperties(request.VisitRequest.First());
                    VisitRequestPresent.Update(request.VisitRequest.First());
                }
                else if (request.RequestType == (int)RequestType.SiteBorrow)
                {
                    RentRequest.RentRequestData.CopeProperties(request.RentRequest.First());
                    RentRequestPresent.Update(request.RentRequest.First());
                }
                else if (request.RequestType == (int)RequestType.Testing)
                {
                    TestingRequest.TestPersonUpdate();
                    TestingRequest.TestRequestData.CopeProperties(request.TestRequest.First());
                    TestRequestPresent.Update(request.TestRequest.First());
                }
                RequestPresent.Update(request);
            }

            else
            {
                Model.Request request = RequestBasic.RequestData;
                request.Status = (int)status;
                if (request.RequestType == (int)RequestType.Visit)
                {
                    request.VisitRequest.Add(VisitRequest.VisitRequestData);
                }
                else if (request.RequestType == (int)RequestType.SiteBorrow)
                {
                    request.RentRequest.Add(RentRequest.RentRequestData);
                }
                else if (request.RequestType == (int)RequestType.Testing)
                {
                    request.TestRequest.Add(TestingRequest.TestRequestData);
                }
                RequestPresent.Create(request);
            }

        }

        protected void btnApprov_Click(object sender, EventArgs e)
        {
            this.btnApprov.Enabled = false;
            this.btnRejected.Enabled = false;
            this.btnAskForMore.Enabled = false;
            this.ExecApproval(RequestStatus.Approved, this.Id, Comments);

        }

        protected void btnReject_click(object sender, EventArgs e)
        {
            this.ExecApproval(RequestStatus.Rejected, this.Id, Comments);
        }

        protected void btnAskForMore_Click(object sender, EventArgs e)
        {
            this.ExecApproval(RequestStatus.AskForMore, this.Id, Comments);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var type = this.txtStatus.Text;

            if (string.IsNullOrEmpty(this.NewComments.Text))
            {
                return;
            }
            var commentContents = Server.HtmlEncode(CurrentUserName + ":" + this.NewComments.Text + "<br/>");
            Comments = commentContents;
            if (type == RequestStatus.Rejected.ToString())
            {
                this.ExecApproval(RequestStatus.Rejected, this.Id, Comments);
            }

            if (type == RequestStatus.AskForMore.ToString())
            {
                this.ExecApproval(RequestStatus.AskForMore, this.Id, Comments);
            }
            Response.Redirect("/MyWork/View.aspx");
        }

        protected void ExecApproval(RequestStatus ApprovalType, int RequestId, string comments)
        {
            var content = new StringBuilder();
            var dns = Request.Url.Host;
            var userNameCN = string.Empty;
            var userNameEN = string.Empty;
            var linkAddress = string.Empty;
            var linkEmail = string.Empty;
            var linkPhone = string.Empty;
            var requst = RequestPresent.GetById(RequestId);
            var requstLab = LabPresent.GetById(requst.LabId);
            var requestUserEmail = RequestPresent.GetRequestUserEmail(requst.RequestUserId);

            RequestPresent.GetUserNameById(requst.RequestUserId, out userNameCN, out userNameEN);
            RequestPresent.GetEmailPhoneById(RequestId, out linkEmail, out linkPhone);

            if (ApprovalType == RequestStatus.Approved)
            {
                linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true, Request.Url.Port, Language.EN, true);
                content.Append(userNameEN + "^" + requstLab.Name + "^" + requst.RequestDate.Year + "^" + requst.RequestDate.Month + "^"
                    + requst.RequestDate.Day + " " + Utility.Helper.FormateTimeSpan(requst.StartTime) + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone + "^");
                linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true, Request.Url.Port, Language.CN, true);
                content.Append(userNameCN + "^" + requstLab.Name + "^" + requst.RequestDate.Year + "^" + requst.RequestDate.Month + "^"
                    + requst.RequestDate.Day + " " + Utility.Helper.FormateTimeSpan(requst.StartTime) + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone);
                RequestPresent.UpdateRequestById(RequestId, (int)(RequestStatus.Approved), Comments);
                var ccList = RequestPresent.GetLabManagerAndSiteManagerEmail(requstLab.LabId, requstLab.LocationId);
                if (ccList == null)
                {
                    ccList = new List<string>();
                }

                MailPresent.SendMail(EmailTemplate.ApprovedReminder, content.ToString(), requestUserEmail, ccList);
            }
            else if (ApprovalType == RequestStatus.Rejected)
            {
                content.Clear();
                linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true, Request.Url.Port, Language.EN, true);
                content.Append(userNameEN + "^" + requstLab.Name + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone + "^");
                linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true, Request.Url.Port, Language.CN, true);
                content.Append(userNameCN + "^" + requstLab.Name + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone);

                RequestPresent.UpdateRequestById(RequestId, (int)(RequestStatus.Rejected), Comments);
                MailPresent.SendMail(EmailTemplate.RejectedReminder, content.ToString(), requestUserEmail, new List<string>());
            }
            else
            {
                content.Clear();
                linkAddress = "http://" + dns + ":" + Request.Url.Port + "/Request/Apply.aspx?id=" + requst.RequestId + "&language=" + Language.EN.ToString() + "&read=false";
                content.Append(userNameEN + "^" + requstLab.Name + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone + "^");
                linkAddress = "http://" + dns + ":" + Request.Url.Port + "/Request/Apply.aspx?id=" + requst.RequestId + "&language=" + Language.CN.ToString() + "&read=false";
                content.Append(userNameCN + "^" + requstLab.Name + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone);
                RequestPresent.UpdateRequestById(RequestId, (int)(RequestStatus.AskForMore), Comments);
                MailPresent.SendMail(EmailTemplate.AskForMoreReminder, content.ToString(), requestUserEmail, new List<string>());
            }
            Response.Redirect("/MyWork/View.aspx");
        }

        protected void SaveDraftOrAskForMoreRequest(int RequestId)
        {
            RequestPresent.UpdateRequestById(RequestId, (int)(RequestStatus.Pending), Comments);
            Response.Redirect("/MyWork/View.aspx");
        }

        private void InitialButton()
        {
            this.btnSaveDraft.Visible = false;
            this.btnSave.Visible = false;
            this.btnCancel.Visible = false;

            this.btnApprov.Visible = false;
            this.btnRejected.Visible = false;
            this.btnAskForMore.Visible = false;
            this.commentValidate.Enabled = false;

            if (this.Id == 0)
            {
                this.btnSaveDraft.Visible = true;
                this.btnSave.Visible = true;
                this.btnCancel.Visible = true;
                this.btnReturn.Visible = false;
            }
            if (this.Id != 0 && this.IsApprover)
            {
                var requst = RequestPresent.GetById(this.Id);
                if (requst.Status == (int)RequestStatus.Pending)
                {
                    this.btnApprov.Visible = true;
                    this.btnRejected.Visible = true;
                    this.btnAskForMore.Visible = true;
                    this.commentValidate.Enabled = true;
                    this.btnRejected.Attributes.Add("onClick", "return false");
                    this.btnAskForMore.Attributes.Add("onClick", "return false");
                }
            }
            if (this.Id != 0 && IsCurrentApplyUser)
            {
                var requestStatus = this.GetRequestStatus(this.Id);

                if (!string.Equals(GetQueryString("pageStatus"), PageStatus.Readonly.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    if (requestStatus == RequestStatus.Draft)
                    {
                        this.PageStatus = PageStatus.Edit;
                        this.btnReturn.Visible = false;
                        this.btnSaveDraft.Visible = true;
                        this.btnSave.Visible = true;
                        this.btnCancel.Visible = true;
                        this.commentValidate.Enabled = false;
                    }
                    if (requestStatus == RequestStatus.AskForMore)
                    {
                        this.PageStatus = PageStatus.Readonly;
                        this.btnReturn.Visible = false;
                        this.btnSave.Visible = false; ;
                        this.btnCancel.Visible = true;
                        this.btnSaveAskForMore.Visible = true;
                        this.commentValidate.Enabled = false;
                    }
                }
                else
                {
                    this.PageStatus = PageStatus.Readonly;
                    this.btnReturn.Visible = true;
                }

            }

        }

        private RequestStatus GetRequestStatus(int requestId)
        {
            var request = RequestPresent.GetById(requestId);
            switch (request.Status)
            {
                case (int)RequestStatus.Draft:
                    return RequestStatus.Draft;
                case (int)RequestStatus.AskForMore:
                    return RequestStatus.AskForMore;
                default:
                    return RequestStatus.Pending;
            }


        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/MyWork/View.aspx");
        }
        protected void btnSaveAskForMore_Click(object sender, EventArgs e)
        {
            var request = RequestPresent.GetById(this.Id);
            var commentBox = this.RequestBasic.FindControl("txtComments") as TextBox;
            request.Comments += Server.HtmlEncode(CurrentUserName + ":" + commentBox.Text + "<br/>");
            request.Status = (int)RequestStatus.Pending;
            RequestPresent.Update(request);

            var dns = Request.Url.Host;
            //var userNameCN = string.Empty;
            //var userNameEN = string.Empty;
            var linkAddress = string.Empty;
            var linkEmail = string.Empty;
            var linkPhone = string.Empty;
            var requst = RequestPresent.GetById(request.RequestId);
            var requstLab = LabPresent.GetById(requst.LabId);
            var requestUserEmail = RequestPresent.GetRequestUserEmail(requst.RequestUserId);

            //RequestPresent.GetUserNameById(requst.RequestUserId, out userNameCN, out userNameEN);
            linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true, Request.Url.Port, Language.EN, false);
            RequestPresent.GetEmailPhoneById(request.RequestId, out linkEmail, out linkPhone);
            var content = new StringBuilder(requstLab.Name + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone + "^");
            linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true, Request.Url.Port, Language.CN, false);
            content.Append(requstLab.Name + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone);
            var centerManagerEmails = RequestPresent.GetCenterManagerEmails(int.Parse(ConfigurationManager.AppSettings["CenterManagerRoleId"]));
            MailPresent.SendMail(EmailTemplate.ApprovalReminderAfterAskForMore, content.ToString(), centerManagerEmails, new List<string>());
            Response.Redirect("/MyWork/View.aspx");
        }
        private string Comments { set; get; }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("/Calendar/View.aspx");
        }

    }
}